package com.tensquare.friend.controller;

import com.tensquare.friend.client.UserClient;
import com.tensquare.friend.service.FriendService;
import entity.Result;
import entity.StatusCode;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/friend")
@CrossOrigin
public class FriendController {

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private FriendService friendService;


    @Autowired
    private UserClient userClient;



    @RequestMapping(value = "/like/{friendid}/{type}",method = RequestMethod.PUT)
    public Result addFriend(@PathVariable String friendid,@PathVariable String type){

        //验证是否登陆
        Claims claims =(Claims) request.getAttribute("claims_user");

        if (claims ==null){
           return new Result(false, StatusCode.ERROR,"权限不足");
       }
        String userid = claims.getId();
        //判断是添加好友还是添加非好友
        if(type==null){
            return new Result(false, StatusCode.ERROR,"参数异常");
        }
        if (type.equals("1")){
            //添加好友
          int flag= friendService.addFirend(userid,friendid);

          if (flag==0){
              return new Result(false, StatusCode.REPERROR,"已经添加此好 友");
          }
             if (flag==1){
                 userClient.updatefanscountandfollowcount(userid,friendid,1);
              return new Result(false, StatusCode.REPERROR,"添加好 友成功");
          }
        }else if(type.equals("2")) {
            //添加非好友
            System.out.println(22222);
           int  flag= friendService.addnofriend(userid,friendid);
            System.out.println(333333);
            if (flag==0){
                return new Result(false, StatusCode.REPERROR,"已经是非好 友");
            }
            if (flag==1){
                return new Result(false, StatusCode.REPERROR,"成功添加非好友");
            }

        }
        return new Result(false, StatusCode.ERROR,"参数异常");

    }


    @RequestMapping(value = "/{friendid}",method = RequestMethod.DELETE)
    public Result addFriend(@PathVariable String friendid){
        //验证是否登陆
        Claims claims =(Claims) request.getAttribute("claims_user");

        if (claims ==null){
            return new Result(false, StatusCode.ERROR,"权限不足");
        }
        String userid = claims.getId();

        friendService.deleteFriend(userid,friendid);
        userClient.updatefanscountandfollowcount(userid,friendid,-1);

        return new Result(true,StatusCode.OK,"删除成功");


    }






    }
